<?php

namespace App\Http\Controllers\Auth;

use Auth;
use JWTAuth;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

/**
 * 用户登录控制器
 *
 * @package App\Http\Controllers\Auth
 * @author George <george@betterde.com>
 */
class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 处理用户登录逻辑
     *
     * Date: 2018/1/25
     * @author George
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    'error' => '认证失败，用户名或密码不正确'
                ], 401);
            }
        } catch (JWTException $exception) {
            return response()->json([
                'error' => '未知错误，请稍后再试'
            ], 500);
        }

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => config('jwt.ttl') * 60
        ]);
    }

    /**
     * 注销用户
     *
     * Date: 2018/1/25
     * @author George
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        try {
            $this->guard()->logout();
        } catch (Exception $exception) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Error'
            ], 500);
        }
        return response()->json([
            'status' => 'success',
            'message' => '注销成功'
        ]);
    }

    /**
     * 定义用于验证的用户的字段
     *
     * Date: 2018/1/25
     * @author George
     * @return string
     */
    public function username()
    {
        return 'staffid';
    }

    /**
     * 定义默认的Guard
     *
     * Date: 2018/1/25
     * @author George
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
     */
    public function guard()
    {
        return Auth::guard('api');
    }
}
